package cn.cosmosx.controller.cashflow;

import cn.cosmosx.base.pdf.Type;
import cn.cosmosx.base.pdf.bean.AlipayFlow;
import cn.cosmosx.base.pdf.bean.WxFlow;
import cn.cosmosx.base.pdf.flow.AlipayFlowUtil;
import cn.cosmosx.base.pdf.flow.FlowWrapper;
import cn.cosmosx.base.pdf.flow.WxFlowUtil;
import cn.cosmosx.base.util.FileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Api(tags = "现金流水")
@Slf4j
@RestController
@RequestMapping(value = "/cash/flow")
public class CashFlowController {

    @ApiOperation(value = "支付宝现金流水")
    @PostMapping("/alipay")
    public Map<String, Object> alipay(@RequestPart("file") MultipartFile file) {
        Map<String, Object> data = new HashMap<>();
        FlowWrapper<AlipayFlow> wrapper = AlipayFlowUtil.read(FileUtils.transferToFile(file));
        data.put("姓名", wrapper.getRealName());
        data.put("账户", wrapper.getAccount());
        data.put("证件号码", wrapper.getIdCardNUmber());
        data.put("起始日期", wrapper.getStartDate());
        data.put("结束日期", wrapper.getEndDate());
        data.put("流水合计（收入）", sumAlipayFlow(wrapper, Type.IN));
        data.put("流水合计（支出）", sumAlipayFlow(wrapper, Type.OUT));
        data.put("流水合计（其他）", sumAlipayFlow(wrapper, Type.OTHER));
        data.put("流水明细", wrapper.getDetails());
        return data;
    }

    @ApiOperation(value = "微信现金流水")
    @PostMapping("/wx")
    public Map<String, Object> wx(@RequestPart("file") MultipartFile file) {
        Map<String, Object> data = new HashMap<>();
        FlowWrapper<WxFlow> wrapper = WxFlowUtil.read(FileUtils.transferToFile(file));
        data.put("姓名", wrapper.getRealName());
        data.put("账户", wrapper.getAccount());
        data.put("证件号码", wrapper.getIdCardNUmber());
        data.put("起始日期", wrapper.getStartDate());
        data.put("结束日期", wrapper.getEndDate());
        data.put("流水合计（收入）", sumWxFlow(wrapper, Type.IN));
        data.put("流水合计（支出）", sumWxFlow(wrapper, Type.OUT));
        data.put("流水合计（其他）", sumWxFlow(wrapper, Type.OTHER));
        data.put("流水明细", wrapper.getDetails());
        return data;
    }

    double sumAlipayFlow(FlowWrapper<AlipayFlow> wrapper, Type type) {
        return wrapper.getDetails().stream().filter(f -> type.getValue().equals(f.getOutInType()))
                .mapToDouble(f -> Double.parseDouble(f.getAmount())).sum();
    }
    double sumWxFlow(FlowWrapper<WxFlow> wrapper, Type type) {
        return wrapper.getDetails().stream().filter(f -> type.getValue().equals(f.getOutInType()))
                .mapToDouble(f -> Double.parseDouble(f.getAmount())).sum();
    }
}
